package top.kaoshanji.p1ch11a;

import org.apache.hc.core5.http.ContentType;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.charset.StandardCharsets;

/**
 * 代码清单-p1ch11a-375页a：前端搜索引擎
 * URL访问地址：/searchView
 * @author kaoshanji
 * ^_^
 * create time 2025/4/5 15:34
 */
public class SearchView extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 设置请求对象的编码
        req.setCharacterEncoding(StandardCharsets.UTF_8.name());

        // 设置响应对象的编码和内容格式
        resp.setContentType(ContentType.TEXT_PLAIN.toString());
        PrintWriter out = resp.getWriter();

        // 从请求属性取得搜索结果...放进去是什么，取出来的才是什么
        String[] results = (String[]) req.getAttribute("results");

        if (results == null) {
            out.println("No results.");
            out.println("Did you accidentally access this servlet directly?");
        }
        else {
            out.println("Results:");
            for (int i = 0; i < results.length; i++) {
                out.println(results[i]);
            }
        }

        out.println();
        out.println("Request URI: " + req.getRequestURI());
        out.println("Context Path: " + req.getContextPath());
        out.println("Servlet Path: " + req.getServletPath());
        out.println("Path Info: " + req.getPathInfo());
        out.println("Query String: " + req.getQueryString());

    }

}
